<template>
    <div>
        <el-form :inline="true" :model="searchMap" style="margin: 20px;" ref="searchFormRef">
            <el-form-item prop="teacher_id" style="width: 200px;">
                <el-select v-model="searchMap.teacher_id" placeholder="根据授课教师查询" clearable>
                    <el-option v-for="option in teacherOptions" :label="option.name" :value="option._id"
                        :key="option._id" />
                </el-select>
            </el-form-item>
            <el-form-item prop="manager_id" style="width: 200px;">
                <el-select v-model="searchMap.manager_id" placeholder="根据学管查询" clearable>
                    <el-option v-for="option in managerOptions" :label="option.name" :value="option._id"
                        :key="option._id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getClassList">查询</el-button>
                <el-button @click="resetForm(searchFormRef)">重置</el-button>
                <el-button type="primary" @click="handleAdd">添加班级</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="classList" style="width: 100%" height="500px">
            <el-table-column label="序号" width="80" type="index"></el-table-column>
            <el-table-column label="班级名字" prop="classname"></el-table-column>
            <el-table-column label="学管名字" prop="manager_id" :formatter="formatManager"></el-table-column>
            <el-table-column label="授课教师" prop="teacher_id" :formatter="formatTeacher"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row._id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

        <!-- 添加或编辑 -->
        <el-dialog v-model="classFormVisible" title="添加/编辑班级" width="500">
            <el-form :model="updateClass" :rules="rules" ref="classFormRef" style="width: 400px" label-width="100px"
                label-position="right">
                <el-form-item label="班级名称" prop="classname">
                    <el-input v-model="updateClass.classname" />
                </el-form-item>
                <el-form-item label="任课教师" prop="teacher_id">
                    <el-select v-model="updateClass.teacher_id" placeholder="请选择任课教师">
                        <el-option v-for="option in teacherOptions" :label="option.name" :value="option._id"
                            :key="option._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学管" prop="manager_id">
                    <el-select v-model="updateClass.manager_id" placeholder="请选择学管">
                        <el-option v-for="option in managerOptions" :label="option.name" :value="option._id"
                            :key="option._id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        @click="updateClass._id == null ? addData(classFormRef) : updateData(classFormRef)">确认</el-button>
                    <el-button @click="classFormVisible = false"> 取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { classInfoData } from '@/api/class/type';
import { nextTick, onMounted, reactive, ref } from 'vue';
//引入班级小仓库
import useClassStore from '@/store/modules/class';
//引入角色小仓库
import useRoleStore from '@/store/modules/role';
//引入用户小仓库
import useUserStore from '@/store/modules/user';
import type { roleInfoData } from '@/api/role/type';
import type { userInfoData } from '@/api/user/type';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';

const classStore = useClassStore();
const roleStore = useRoleStore();
const userStore = useUserStore();
//角色数组
const roleOptions = ref<roleInfoData[]>([])
//用户数组
const userOptions = ref<userInfoData[]>([])
//教师id
const teacher_role_id = ref("")
//学管id
const manager_role_id = ref("")
//教师数组
const teacherOptions = ref<userInfoData[]>([]);
//学管数组
const managerOptions = ref<userInfoData[]>([])
//添加/编辑班级数据收集对象
const updateClass = ref({
    _id: null,
    classname: "",
    teacher_id: "",
    manager_id: "",
})
//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const searchFormRef = ref()
const classFormVisible = ref()
// 表单ref对象
const classFormRef = ref()
//表单校验规则
const rules = reactive<FormRules>({
    classname: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
    teacher_id: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
    manager_id: [{ required: true, message: '请输入班级名称', trigger: 'blur' }]

})


const addData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            classStore.addClass(updateClass.value).then(() => {
                classFormVisible.value = false
                getClassList()
            })
        } else {
            console.log('error submit!')
        }
    })
}


const updateData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            classStore.updateClass(updateClass.value).then(() => {
                classFormVisible.value = false;
                getClassList();
            })
        } else {
            console.log('error submit!')
        }
    })
}

//获取角色列表
const roleList = () => {
    return new Promise((resolve, _reject) => {
        if (roleStore.roles && roleStore.roles.length) {
            roleOptions.value = roleStore.roles;
            roleOptions.value.forEach((item) => {
                if (item.name == "教师") {
                    teacher_role_id.value = item._id as string;
                } else if (item.name == "学管") {
                    manager_role_id.value = item._id as string;
                }
            });
            resolve(true);
        } else {
            roleStore.roleList().then(() => {
                roleOptions.value = roleStore.roles as roleInfoData[];
                roleOptions.value.forEach((item) => {
                    if (item.name == "教师") {
                        teacher_role_id.value = item._id as string;
                    } else if (item.name == "学管") {
                        manager_role_id.value = item._id as string;
                    }
                });
            });
            resolve(true)
        }
    })
}
//获取用户数组
const getUserList = () => {
    return new Promise((resolve, _reject) => {
        if (userStore.users && userStore.users.length) {
            userOptions.value = userStore.users;
            userOptions.value.forEach((item) => {
                if (item.role_id == teacher_role_id.value) {
                    teacherOptions.value.push(item)
                } else if (item.role_id == manager_role_id.value) {
                    managerOptions.value.push(item)
                }
            });
            resolve(true);
        } else {
            userStore.getUserAll().then(() => {
                userOptions.value = userStore.users;
                userOptions.value.forEach((item) => {

                    if (item.role_id == teacher_role_id.value) {
                        teacherOptions.value.push(item)

                    } else if (item.role_id == manager_role_id.value) {
                        managerOptions.value.push(item)
                    }
                });
            });
            resolve(true)
        }
    })
}

//格式化教师
const formatTeacher = (
    _row: any,
    _colum: any,
    cellValue: string,
    _index: number
) => {
    let teacher = teacherOptions.value.find(
        (item) => item._id == cellValue
    );
    return teacher?.name;
}


//格式化学管
const formatManager = (
    _row: any,
    _colum: any,
    cellValue: string,
    _index: number
) => {
    let manager = managerOptions.value.find(
        (item) => item._id == cellValue
    );
    return manager?.name;
}

const classList = ref<classInfoData[]>([])

//编辑
const handleEdit = (_id: string) => {
    handleAdd();
    classStore.getClassById(_id).then((response) => {
        //@ts-ignore
        updateClass.value = response
    })
}
//删除
const handleDelete = (_id: string) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            classStore.deleteClass(_id).then(() => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });
                getClassList();
            })
        })
        .catch(() => { })
}
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)


const handleSizeChange = (val: number) => {
    pageSize.value = val
    getClassList()
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getClassList()
}
//打开添加班级弹窗
const handleAdd = () => {
    classFormVisible.value = true
    updateClass.value = {
        _id: null,
        classname: '',
        teacher_id: '',
        manager_id: ''
    }
    nextTick(() => {
        classFormRef.value.resetFields()
    })
}
//条件筛选对象
const searchMap = ref({
    teacher_id: "",
    manager_id: "",
})
const getClassList = () => {
    classStore.getClassList({
        page: currentPage.value, size: pageSize.value, searchMap: searchMap.value
    }).then((response) => {
        classList.value = classStore.classes
        total.value = response?.total as number
    })
}
onMounted(() => {
    roleList().then(() => {
        getUserList().then(() => {
            getClassList()
        })
    })
})
</script>

<style scoped></style>